package com.kehao.newcoder;


import org.junit.Test;

import java.util.List;
import java.util.Stack;

public class NC40Solution {

    private class ListNode {
        int val;
        ListNode next = null;
        ListNode(int  val){
            this.val = val;
        }
    }


    public ListNode addInList(ListNode head1, ListNode head2) {
        // write code here
        Stack<Integer> s1 = new Stack<>();
        Stack<Integer> s2 = new Stack<>();
        ListNode p = head1;
        while (p != null) {
            s1.push(p.val);
            p = p.next;
        }
        p = head2;
        while (p != null) {
            s2.push(p.val);
            p = p.next;
        }
        int another = 0;
        ListNode head = new ListNode(0);
        while((!s1.isEmpty())&&(!s2.isEmpty())) {
            int i1 = s1.pop();
            int i2 = s2.pop();
            int result = i1 + i2 + another;
            another = result / 10;
            if (result > 9) {
                result = result % 10;
            }
            p = new ListNode(result);
            p.next = head.next;
            head.next = p;
        }
        while (!s1.isEmpty()) {
            int i1 = s1.pop();
            int result = i1 + another;
            another = result / 10;
            if (result > 9) {
                result = result % 10;
            }
            p = new ListNode(result);
            p.next = head.next;
            head.next = p;
        }
        while (!s2.isEmpty()) {
            int i2 = s2.pop();
            int result = i2 + another;
            another = result / 10;
            if (result > 9) {
                result = result % 10;
            }
            p = new ListNode(result);
            p.next = head.next;
            head.next = p;
        }
        if(another ==0) {
            return head.next;
        }else {
            head.val = another;
            return head;
        }
    }

    @Test
    public void test(){
        int[] arr1 = {9,3,7};
        int[] arr2 = {6,3};
        ListNode head1 = genListNode(arr1);
        ListNode head2 = genListNode(arr2);
        ListNode listNode = addInList(head1, head2);
        listOutput(listNode);
    }

    private ListNode genListNode(int[] arr ){
        ListNode head = new ListNode(0);
        ListNode rear = head;
        for (int i = 0; i < arr.length ;i++) {
            ListNode listNode = new ListNode(arr[i]);
            rear.next = listNode;
            rear = rear.next;
        }
        return head.next;
    }
    private void listOutput(ListNode head){
        while (head!=null){
            System.out.print(head.val+" ");
            head = head.next;
        }
    }
}
